﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.ServiceModel.Web;
using System.Text;
using Core.BusinessLogic.Interfaces;
using Core.BusinessLogic;
using Core.Interfaces;
using Core.Components;
using Core.DataAccess;
using System.Web;
using Core.Common;
using SonCa.SocialNetwork.Web.HelperClass;
using SonCa.SocialNetwork.Profiles.Presenters;
using System.Web.Security;
using SonCa.SocialNetwork.Web.Profiles.Presenters;
using SonCa.SocialNetwork.Web.Friends.Presenters;
using SonCa.SocialNetwork.Web.Chat.Presenters;
using SonCa.SocialNetwork.Web.Accounts.Presenters;
using System.Globalization;
using System.Web.Hosting;
using SonCa.SocialNetwork.Web.Files;

namespace SonCa.SocialNetwork.Web.Services
{
    [ServiceBehavior(IncludeExceptionDetailInFaults = true)]
    [ServiceContract(Namespace = "")]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class AjaxService
    {
        /// <summary>
        /// Service Logout.
        /// </summary>
        [OperationContract]
        public void Logout()
        {
            IAccountService _accountService = new AccountService();
            IUserSession _userSession = new UserSession();
            IStatusChatService _statusChatService = new StatusChatService();

            _statusChatService.UpdateStatusChat(_userSession.CurrentUser.AccountID, false);
            UserChatPresenter.userObj.Remove(UserChatPresenter.userObj.Where(item => item.userID == _userSession.CurrentUser.AccountID.ToString()).FirstOrDefault());
            _accountService.Logout();            
        }

        /// <summary>
        /// Service Save Like Number.
        /// </summary>
        /// <param name="forAccountID"></param>
        /// <param name="statusID"></param>
        /// <returns></returns>
        [OperationContract]
        public bool SaveRating(string forAccountID,string statusID)
        {
            IUserSession _userSession = new UserSession();
            IRatingService _ratingService = new RatingService();
            return _ratingService.SaveRating(new Rating
            {
                CreateByAccountID = _userSession.CurrentUser.AccountID,
                Type = 0,
                SystemObjectID = Convert.ToInt32(forAccountID),
                SystemObjectRecordID = Convert.ToInt64(statusID),
                CreateByAccountName = _userSession.CurrentUser.LastName + " " + _userSession.CurrentUser.MidName + " " + _userSession.CurrentUser.FirstName,
                CreateDate = DateTime.Now
            });
        }

        /// <summary>
        /// Save unlike number.
        /// </summary>
        /// <param name="forAccountID"></param>
        /// <param name="statusID"></param>
        /// <returns></returns>
        [OperationContract]
        public bool SaveUnlike(string forAccountID, string statusID)
        {
            IUserSession _userSession = new UserSession();
            IRatingService _ratingService = new RatingService();
            return _ratingService.SaveRating(new Rating
            {
                CreateByAccountID = _userSession.CurrentUser.AccountID,
                Type = 1,
                SystemObjectID = Convert.ToInt32(forAccountID),
                SystemObjectRecordID = Convert.ToInt64(statusID),
                CreateByAccountName = _userSession.CurrentUser.LastName + " " + _userSession.CurrentUser.MidName + " " + _userSession.CurrentUser.FirstName,
                CreateDate = DateTime.Now
            });                    
        }

        [OperationContract]
        public bool SaveShare(string forAccountID, string statusID)
        {

            return false;
        }

        /// <summary>
        /// Save Comment Of Stautus.
        /// </summary>
        /// <param name="statusID"></param>
        /// <param name="body"></param>
        /// <returns></returns>
        [OperationContract]
        public string SaveComment(string statusID, string body)
        {
            IUserSession _userSession = new UserSession();
            ICommentService _commentService = new CommentService();
            _commentService.SaveComment(new Comment
            {
                CommentByAccountID = _userSession.CurrentUser.AccountID,
                CommentForStatusID = Convert.ToInt32(statusID),
                CreateDate = DateTime.Now,
                SystemObjectID = 5,
                SystemObjectRecordID = Convert.ToInt64(statusID),
                Body = body,
                CommentByAccountName = _userSession.CurrentUser.LastName + " " + _userSession.CurrentUser.MidName + " " + _userSession.CurrentUser.FirstName
            });
            return @"<div class='mgbot15'><img class='img cpos_1' width='35' height='35' src='../Images/ProfileAvatar/ProfileImage.aspx?AccountID=" + _userSession.CurrentUser.AccountID + "'>" + @"<span class='title10'>"
                + _userSession.CurrentUser.LastName + "&nbsp;" + _userSession.CurrentUser.MidName + "&nbsp;" + _userSession.CurrentUser.FirstName + "</span>" + "&nbsp;&nbsp;" + body + "<div>one second ago</div>" + "</div><div class='clearer'></div>";
        }


        /// <summary>
        /// Save Friends Invitaion.
        /// </summary>
        /// <param name="accountID"></param>
        [OperationContract]
        public void SendInvitationRequest(string accountID)
        {
            if (!string.IsNullOrEmpty(accountID))
            {
                IUserSession _userSession = new UserSession();
                IFriendInvitationService _friendInvitationService = new FriendInvitationService();
                _friendInvitationService.SaveFriendInvitation(new FriendsInvitation { CreateDate = DateTime.Now, AccountID = _userSession.CurrentUser.AccountID, BecameAccountID = Convert.ToInt32(accountID) });
            }
        }

        /// <summary>
        /// Save Status.
        /// </summary>
        /// <param name="statusText"></param>
        /// <returns></returns>
        [OperationContract]
        public string SaveStatus(string statusText, string statusType, string fileNameUpdate)
        {
            if (statusType == "1" && statusText.Length == 0)
                return "";
            IUserSession _userSession = new UserSession();
            IStatusUpdateService _statusUpdateService = new StatusUpdateService();
            ILevelService _levelService = new LevelService();
            IAccountService _accountService = new AccountService();
            IFileService _fileService = new FileService();

            long statusUpdateID = _statusUpdateService.SaveStatusUpdate(new StatusUpdate { CreateDate = DateTime.Now, AccountID = _userSession.CurrentUser.AccountID, Status = statusText, StatusType = Convert.ToInt32(statusType) });
            _fileService.UpdateIsPublicResourceByFileName(fileNameUpdate);

            string level = _levelService.GetLevelPathByLevelID(Convert.ToInt32(_userSession.CurrentUser.LevelID));
            int score = _accountService.GetScoreByAccountID(_userSession.CurrentUser.AccountID);
            string fullName = _userSession.CurrentUser.LastName + " " + _userSession.CurrentUser.MidName + " " + _userSession.CurrentUser.FirstName;
            //string folder = DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString(); 
            string fileName = ReceiveFile.guiName;
            string file = "";
            if (statusType == "2")
                file = @"<a id='rptFriend_pdProfileDisplay_0_rptPhotos_0_linkPhotos_0' href='#'>
                            <img src='../Files/Photos/" + fileName + @"'>
                        </a>";
            else if (statusType == "3")
                file = @"<video id='video' class='video-js vjs-default-skin' controls preload='none' width='300' height='200'
                            poster='../img/slide.jpg'
                            data-setup='{'example_option':true}'>
                            <source src='../Files/Videos/" + fileName + @".mp4' type='video/mp4; codecs='avc1.42E01E, mp4a.40.2'' />
                            <source src='../Files/Videos/" + fileName + @".webm' type='video/webm; codecs='vp8, vorbis'' />
                            <source src='../Files/Videos/" + fileName + @".ogg' type='video/ogg; codecs='theora, vorbis'' />
                            <object classid='clsid:d27cdb6e-ae6d-11cf-96b8-444553540000' codebase='http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,0,0' width='300' height='200' align='middle'>
                                <param name='expressinstall' value='../css/expressInstall.swf'>
                                <param name='swfversion' value='9.0.0'>
                                <param name='allowScriptAccess' value='sameDomain' />
                                <param name='movie' value='../Files/Videos/" + fileName + @".swf' />
                                <param name='quality' value='high' />
                                <embed id='video_source_4' src='' quality='high' width='300' height='200' name='tech' align='middle' allowScriptAccess='sameDomain' type='application/x-shockwave-flash' pluginspage='http://www.macromedia.com/go/getflashplayer' />                    
                            </object>
                        </video>";
            else if (statusType == "4")
                file = @"<audio controls>
                          <source src='../Files/Audios/" + fileName + @".mp3' type='audio/mpeg'>
                          <source src='../Files/Audios/" + fileName + @".wav' type='audio/wav'>
                          <source src='../Files/Audios/" + fileName + @".ogg' type='audio/ogg'>
                          <object height='50' width='100' data='../Files/Audios/" + fileName + @".mp3'></object>
                          Your browser does not support this audio format.
                        </audio>";
            return @"<div class='mgtop30'>
                        <div class='innermgtop30'>
                            <div class='box_181 cpos_1'><div class='w62 cpos_1'>
                                <img style='height:62px;width:62px;' src='../Images/ProfileAvatar/ProfileImage.aspx?AccountID="+ _userSession.CurrentUser.AccountID +@"'/>
                                <div>
                                    <img src='../img/"+ level +@"' />
                                    <strong>"+ score +@"</strong>
                                </div>                                
                            </div>
                        </div>                        
                        <div id='friendDisplay' class='box_320 cpos_2'>
                            <div>
                                <div style='width: 25%' class='cpos_1 title7'>
                                    <span id='rptFriend_pdProfileDisplay_5_lblFriend_5'>" + fullName + @"</span>
                                </div>                                    
                            </div>
                            <div class='clearer'></div>
                            <div class='mgtop10'>
                                <span id='rptFriend_pdProfileDisplay_5_lblStatus_5'>" + statusText + @"</span>
                            </div>
                            "+ file +@"
                            <div class='mgtop10'>
                                <div class='cpos_1 icon_like title9'>
                                    <a class='"+ _userSession.CurrentUser.AccountID +";"+ statusUpdateID +@"' onclick='javascript:Rating(this);return false;' style='cursor:pointer'>like</a><br>
                                    [<span class='title10'>0</span>]
                                </div>
                                <div class='cpos_1 icon_like title9 mgleft5'>
                                    <a class='" + _userSession.CurrentUser.AccountID + ";" + statusUpdateID + @"' onclick='javascript:Unlike(this);return false;' style='cursor:pointer'>unlike</a><br>
                                    [<span class='title10'>0</span>]
                                </div>
                                <div class='clearer'></div>
                            </div>
                            <div class='mgtop10'>
                                <div style=' border: 1px solid #d9d9d9;' class='mgbot10'>
                                    <img style='height:35px;width:35px;' src='../Images/ProfileAvatar/ProfileImage.aspx?AccountID=" + _userSession.CurrentUser.AccountID + "'" + @"class='img cpos_1' id='rptFriend_pdProfileDisplay_5_rptComment_5_CommentControl1_0_imgCommentAvatar_0'>
                                    <input type='text' style='height:29px;width:84%;border: 0 solid #d9d9d9;' onkeypress='return PostComment(event,this);return false;' placeholder='Your Comment ........' class='66' id='txtMyComment'>
                                <div class='clearer'></div>
                            </div>                    
                        </div>
                    </div>
                    <div class='clearer'></div>
                </div>
            </div>";
        }        

        /// <summary>
        /// Auto refresh friends invitation.
        /// </summary>
        /// <param name="accountID"></param>
        /// <returns></returns>
        [OperationContract]
        public string RefreshCounter(string accountID)
        {
            if (!string.IsNullOrEmpty(accountID))
            {
                IFriendInvitationService _friendsService = new FriendInvitationService();
                int countRequest = _friendsService.CountFriendRequestInvitation(Convert.ToInt32(accountID));

                IMessageService _messageService = new MessageService();
                int countMessage = _messageService.CountMessages(Convert.ToInt32(accountID));

                if(countRequest + countMessage > 0)
                    return (countRequest + countMessage).ToString();                
            }
            return "";
        }

        /// <summary>
        /// Auto refresh message.
        /// </summary>
        /// <param name="accountID"></param>
        /// <returns></returns>
        //[OperationContract]
        //public string RefreshCountMessage(string accountID)
        //{
            
        //    return "";
        //}

        /// <summary>
        /// Save accept friends.
        /// </summary>
        /// <param name="accountID"></param>
        /// <returns></returns>
        [OperationContract]
        public bool AcceptFriends(string accountID)
        {
            if (!string.IsNullOrEmpty(accountID))
            {
                IFriendInvitationService _friendInvitationService = new FriendInvitationService();
                IFriendService _friendService = new FriendService();
                IMessageService _messageService = new MessageService();
                IUserSession _userSession = new UserSession();

                _friendInvitationService.CleanUpFriendInvitionByBecameID(Convert.ToInt32(accountID));
                _messageService.SaveMessage(new Message { AccountID = Convert.ToInt32(accountID), IsRead = false, FriendAccountID = _userSession.CurrentUser.AccountID });
                _friendService.AddFriendByAccountID(new Friend { AccountID = _userSession.CurrentUser.AccountID, CreateDate = DateTime.Now, MyFriendsAccountID = Convert.ToInt32(accountID) });                
                return true;
            }
            return false;
        }

        /// <summary>
        /// Save reject friends.
        /// </summary>
        /// <param name="accountID"></param>
        /// <returns></returns>
        [OperationContract]
        public bool RejectFriends(string accountID)
        {
            if (!string.IsNullOrEmpty(accountID))
            {
                IFriendInvitationService _friendInvitationService = new FriendInvitationService();
                IFriendService _friendService = new FriendService();
                IUserSession _userSession = new UserSession();
                _friendInvitationService.CleanUpFriendInvitionByBecameID(Convert.ToInt32(_userSession.CurrentUser.AccountID));
                return true;
            }
            return false;
        }


        /// <summary>
        /// Check User In Use.
        /// </summary>
        /// <param name="username"></param>
        /// <returns></returns>
        [OperationContract]
        public bool CheckUsernameInUse(string username)
        {
            if (!string.IsNullOrEmpty(username))
            {
                IAccountService srv = new AccountService();
                return srv.UsernameInUse(username);
            }
            else
            {
                return false;
            }
        }


        /// <summary>
        /// Check Email In Use.
        /// </summary>
        /// <param name="email"></param>
        /// <returns></returns>
        [OperationContract]
        public bool CheckEmailInUse(string email)
        {
            if (!string.IsNullOrEmpty(email))
            {
                IAccountService srv = new AccountService();
                return srv.EmailInUse(email);
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        /// Check Password.
        /// </summary>
        /// <param name="accountID"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        [OperationContract]
        public string CheckPassword(string accountID, string password)
        {            
            if (!string.IsNullOrEmpty(accountID) && !string.IsNullOrEmpty(password))
            {                
                IAccountService srv = new AccountService();
                IUserSession _userSession = new UserSession();

                bool result = srv.CheckPassword(accountID, Extensions.Encrypt(password,_userSession.CurrentUser.Plaintext));
                if (result)
                    return "ok";
            }
            return "";
        }


        /// <summary>
        /// Change Password.
        /// </summary>
        /// <param name="accountID"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        [OperationContract]
        public string ChangePassword(string accountID, string password)
        {
            if (!string.IsNullOrEmpty(accountID))
            {
                IAccountService srv = new AccountService();
                IUserSession _userSession = new UserSession();

                bool result = srv.UpdatePassword(Convert.ToInt32(accountID), Extensions.Encrypt(password,_userSession.CurrentUser.Plaintext));
                if (result)
                    return "ok";
            }
            return "";
        }

        /// <summary>
        /// Reset Password
        /// </summary>
        /// <param name="email"></param>
        /// <returns></returns>
        [OperationContract]
        public int ResetPassword(string email)
        {
            IAccountService _accountService = new AccountService();
            IEmail _emailService = new Email();            

            Account account = _accountService.GetAccountByEmail(email);
            if (account != null)
            {
                // Random password
                string ranPassword = _emailService.RandomPassword();

                // Encrypt password
                string encyptPassword = Extensions.Encrypt(ranPassword, account.Plaintext);

                // Update password
                bool updatePass = _accountService.UpdatePassword(account.AccountID, encyptPassword);
                if (updatePass)
                {
                    // Send mail
                    string subject = "MXH Sơn Ca - Lấy lại mật khẩu";
                    string message = "<span>Mật khẩu của bạn là : " + ranPassword + "</span><br/>" +
                                     "<span>Sau khi đăng nhập, bạn nên đổi mật khẩu để tiện cho việc đăng nhập lần sau.</span><br/>" +
                                     "<span>Xin vui lòng không trả lời email này.</span>";
                    try
                    {
                        _emailService.SendEmail(email, "", "", subject, message);
                        return 1;
                    }
                    catch (Exception e) { return 0; }
                }
                else
                    return 0;
            }
            return -1;
        }


        /// <summary>
        /// Recover Password.
        /// </summary>
        /// <param name="email"></param>
        /// <returns></returns>
        [OperationContract]
        public int RecoverPassword(string email)
        {            
            IAccountService _accountService = new AccountService();
            IEmail _emailService = new Email();            

            Account account = _accountService.GetAccountByEmail(email);
            if (account != null)
            {
                string cyphorPass = Extensions.Decrypt(account.Password, account.Plaintext);

                if (!string.IsNullOrEmpty(cyphorPass))
                {
                    // Send mail
                    string subject = "MXH Sơn Ca - Lấy lại mật khẩu";
                    string message = "<span>Mật khẩu của bạn là : " + cyphorPass + "</span><br/>" +
                                     "<span>Xin vui lòng không trả lời email này.</span>";
                    try
                    {
                        _emailService.SendEmail(email, "", "", subject, message);
                        return 1;
                    }
                    catch (Exception e) { return 0; }
                }
                else
                    return 0;
            }
            return -1;
        }        


        /// <summary>
        /// Search Friends.
        /// </summary>
        /// <param name="text"></param>
        /// <returns></returns>
        [OperationContract]
        public string SearchFriends(string text)
        {
            IAccountService _accountService = new AccountService();
            IFriendInvitationService _friendInvitationService = new FriendInvitationService();
            IFriendService _friendService = new FriendService();
            IUserSession _userSession = new UserSession();

            List<Account> lstAccount = _accountService.GetListAccountsByTextSearch(text);
            if (lstAccount.Count > 0)
            {
                // remove current user if exists
                int index = lstAccount.FindIndex(n => n.AccountID == _userSession.CurrentUser.AccountID);
                if (index >= 0)
                    lstAccount.RemoveAt(index);

                List<FriendRequestHelper> lstFriendRequestHelper = new List<FriendRequestHelper>();
                lstAccount.ForEach(n => lstFriendRequestHelper.Add(new FriendRequestHelper
                {
                    AccountID = n.AccountID,
                    FullName = n.LastName + " " + n.MidName + " " + n.FirstName,
                    ImageUrl = string.Format("../Images/ProfileAvatar/ProfileImage.aspx?AccountID={0}", n.AccountID)
                }));

                List<FriendsInvitation> lstFriendInvitation = _friendInvitationService.GetListFriendsRequestByAccountID(_userSession.CurrentUser.AccountID);
                List<Friend> lstFriends = _friendService.GetFriendsByAccountID(_userSession.CurrentUser.AccountID);

                string item = "";
                for (int i = 0; i < lstFriendRequestHelper.Count; i++)
                {
                    string str = "";
                    string str1 = "<img src='../img/icon_addFriend.png' id='imgAddFriend_search_" + i + "' onclick='AddFriend_Search(" + i + "," + lstFriendRequestHelper[i].AccountID + ");' alt='Add Friend' style='cursor:pointer' />";
                    string str2 = "<img src='../img/requestsended.png' alt='Request sended' />";                    
                    str = lstFriendInvitation != null ? lstFriendInvitation.FindIndex(n => n.BecameAccountID == lstFriendRequestHelper[i].AccountID) >= 0 ? str2 : str1 : "";
                    str = lstFriends != null ? lstFriends.FindIndex(n => n.AccountID == lstFriendRequestHelper[i].AccountID || n.MyFriendsAccountID == lstFriendRequestHelper[i].AccountID) >= 0 ? "" : str1 : "";
                    item += "<tr>" +
                                "<td>" +
                                    "<a href='../Personals/PersonalPage.aspx?otherAccountID="+ lstFriendRequestHelper[i].AccountID +"'>" +
                                        "<img src='" + lstFriendRequestHelper[i].ImageUrl + "' width='32px' height='32px' />" +
                                        "<strong>" + lstFriendRequestHelper[i].FullName + "</strong>" +
                                    "</a>" +
                                "</td>" +
                                "<td>" +
                                    "<img src='../img/loading.gif' id='loading_addfriend_search_" + i + "' alt='Loading...' style='display:none' />" +
                                    str +
                                    "<img src='../img/requestsended.png' id='imgRequestSended_search_" + i + "' alt='Request sended' style='display:none' />" +
                                "</td>" +
                            "</tr>";
                }

                string html = "<table style='margin-left:20px;margin-top:10px;width:100%'>" +
                                item +
                              "</table>";
                return html;
            }
            return "Không tìm thấy";
        }

        /// <summary>
        /// Load Message.
        /// </summary>
        /// <param name="accountID"></param>
        /// <returns></returns>
        [OperationContract]
        public string LoadMessage(string accountID)
        {
            IMessageChatService _messageChatService = new MessageChatService();

            List<MessageChat> lstMessageChat = _messageChatService.GetMessageChatByAccountID(Convert.ToInt32(accountID));
            if (lstMessageChat != null)
            {
                string html = "";
                foreach (MessageChat mes in lstMessageChat)
                {
                    html += @"<div>
                                <div style='float:left;margin-left:10px'>
                                    <a href='../Personals/PersonalPage.aspx?otherAccountID=" + mes.AccountIDSent + "'>" + @"
                                        <img width='48px' height='48px' src='../Images/ProfileAvatar/ProfileImage.aspx?AccountID=" + mes.AccountIDSent + "'>" + @"
                                    </a>
                                </div>
                                <div class='message_chat' style='width:85%;margin-left:65px;min-height:30px'>
                                    <span style='padding-left:5px'>" + mes.Message + "</span>" + @"
                                </div>
                                <div style='float:right;margin-top:5px'>" + mes.Time + "</div>" + @"
                                <hr/>
                                <div style='clear:both'></div>
                            </div>";
                    _messageChatService.UpdateMessageChatIsRead(mes.MessageChatID);
                }
                if (html != "")
                    return html;
            }
            return "<div style='text-align:center;color:red'>Không có tin nhắn nào</div>";
        }

        /// <summary>
        /// Receive Upload Photo.
        /// </summary>
        /// <returns></returns>
        [OperationContract]
        public string ReceiveUploadPhoto()
        {                        
            UploadAvatarPresenter upload = new UploadAvatarPresenter();
            return upload.DisplayImgCover();
        }

        [OperationContract]
        public string LoadFriendsChat()
        {
            ListFriendsChatPresenter list = new ListFriendsChatPresenter();            
            IUserSession _userSession = new UserSession();
            IFriendService _fri = new FriendService();
            IAccountService _acc = new AccountService();
            IStatusChatService _stt = new StatusChatService();

            List<FriendRequestHelper> lstFriendChat = list.GetListFriendChat(_userSession.CurrentUser.AccountID);
            if (lstFriendChat.Count > 0)
            {
                string html = "";
                foreach (FriendRequestHelper fr in lstFriendChat)
                {
                    Status status = _stt.GetStatusByAccountID(fr.AccountID);
                    string isOnline = "icon_online";
                    if (!status.AccountStatus)
                        isOnline = "icon_offline";

                    string imgUrl = fr.ImageUrl.Substring(1,fr.ImageUrl.Length - 1);
                    html += "<div class='"+ isOnline +"' id='friendchat_"+ fr.AccountID +"' style='cursor:pointer' onclick='ChatFriend(this);'>" +
                                "<img src='.." + imgUrl +"' style='width:35px;height:35px'/>" +
                                "<strong id='fullname_"+ fr.AccountID +"'>&nbsp;"+ fr.FullName +"</strong>" +
                            "</div><br/>";                                        
                }                
                return html;
            }
            return "Hãy mau kết bạn để thỏa sức chát chit...";
        }

        [OperationContract]
        public string GetFullNameByAccountID(string accountID)
        {
            IAccountService _accountService = new AccountService();

            Account account = _accountService.GetAccountByID(Convert.ToInt32(accountID));
            if (account != null)
                return account.LastName + " " + account.MidName + " " + account.FirstName;
            return "";
        }

        [OperationContract]
        public string SaveMessageChat(string accountIDSent,string message,string accountIDReceive,bool is_read)
        {
            IMessageChatService _messageChatService = new MessageChatService();
            try
            {
                _messageChatService.SaveMessageChat(new MessageChat { AccountIDSent = Convert.ToInt32(accountIDSent), Message = message, AccountIDReceive = Convert.ToInt32(accountIDReceive), Time = DateTime.Now, isRead = is_read });
                return "ok";
            }
            catch (Exception e) { return ""; }
        }

        [OperationContract]
        public string LoadMessageChat(string currentID, string chatToID)
        {
            IMessageChatService _messageChatService = new MessageChatService();

            List<MessageChat> lstMessageChat = _messageChatService.GetMessageChatByAccountID(Convert.ToInt32(currentID), Convert.ToInt32(chatToID));
            string html = "";
            foreach (MessageChat mes in lstMessageChat)
            {                
                if (mes.AccountIDSent == Convert.ToInt32(currentID) && mes.AccountIDReceive == Convert.ToInt32(chatToID))
                {
                    html += @"<div>
                                <div style='float:left;margin-left:5px'>
                                    <a href='#'>
                                        <img width='24px' height='24px' src='../Images/ProfileAvatar/ProfileImage.aspx?AccountID=" + currentID + "'>" + @"
                                    </a>
                                </div>
                                <div class='message_chat' style='width:80%;margin-left:32px;min-height:20px' onmouseover='MouseOverMessageChat(this)' onmouseout='MouseOutMessageChat(this)'>
                                    <span style='padding-left:5px'>" + mes.Message + "</span>" + @"
                                    <div style='float:right;font-size:10px;display:none'>" + mes.Time + "</div>" + @"
                                </div>
                                <div style='clear:both'></div>
                            </div>";
                }
                else if (mes.AccountIDSent == Convert.ToInt32(chatToID) && mes.AccountIDReceive == Convert.ToInt32(currentID))
                {
                    html += @"<div>
                                <div style='float:left;margin-left:5px'>
                                    <a href='#'>
                                        <img width='24px' height='24px' src='../Images/ProfileAvatar/ProfileImage.aspx?AccountID=" + chatToID + "'>" + @"
                                    </a>
                                </div>
                                <div class='message_chat' style='width:80%;margin-left:32px;min-height:20px' onmouseover='MouseOverMessageChat(this)' onmouseout='MouseOutMessageChat(this)'>
                                    <span style='padding-left:5px'>" + mes.Message + "</span>" + @"
                                    <div style='float:right;font-size:10px;display:none'>" + mes.Time + "</div>" + @"
                                </div>
                                <div style='clear:both'></div>
                            </div>";
                }
            }
            return html;
        }

        [OperationContract]
        public string UpdateProfileInfo(string fullname, string birthday,string gender,string email,string aboutme,string interests)
        {
            ProfileEditPresenter _profileEdit = new ProfileEditPresenter();
            return _profileEdit.UpdateProfileInfo(fullname, birthday, gender, email, aboutme, interests);
        }

        [OperationContract]
        public string UpdateEducationInfo(string schoolname, string city, string grade, string startyear, string graduationyear)
        {
            ProfileEditPresenter _profileEdit = new ProfileEditPresenter();
            List<School> schoolList = new List<School>();
            List<AccountSchool> asList = new List<AccountSchool>();
            School school = new School()
            {
                SchoolName = schoolname,
                Grade = Convert.ToByte(grade),
                City = city,
                Country = "VN"
            };
            schoolList.Add(school);

            AccountSchool accSch = new AccountSchool()
            {
                StartYear = Convert.ToInt32(startyear),
                GraduationYear = Convert.ToInt32(graduationyear)
            };
            asList.Add(accSch);

            return _profileEdit.UpdateEducationInfo(schoolList, asList);            
        }

        [OperationContract]
        public string UpdateWorkPlaceInfo(string companyName,string companyAddress,string city,string jobField,string position,string startDate,string endDate)
        {
            ProfileEditPresenter _presenter = new ProfileEditPresenter();
            List<WorkPlace> wpList = new List<WorkPlace>();
            List<AccountWorkPlace> awpList = new List<AccountWorkPlace>();
            WorkPlace wp = new WorkPlace()
            {
                CompanyName = companyName,
                Address = companyAddress,
                JobField = jobField,
                City = city,
                Country = "VN"
            };
            wpList.Add(wp);
            IFormatProvider format = new CultureInfo("vi-VN").DateTimeFormat;
            DateTime dateStart = DateTime.Parse(startDate, format);
            DateTime dateEnd = DateTime.Parse(endDate, format);
            AccountWorkPlace awp = new AccountWorkPlace()
            {
                StartDate = dateStart,
                EndDate = dateEnd,
                Position = position
            };
            awpList.Add(awp);

            return _presenter.UpdateWorkPlaceInfo(wpList, awpList);
        }

        [OperationContract]
        public string UpdateLocationInfo(string locationName,string locationAddress,string city,string startDate,string endDate)
        {
            ProfileEditPresenter _presenter = new ProfileEditPresenter();
            List<Location> locationList = new List<Location>();
            List<AccountLocation> alList = new List<AccountLocation>();
            Location location = new Location()
            {
                LocationName = locationName,
                Address = locationAddress,
                City = city,
                Country = "VN"
            };
            locationList.Add(location);
            IFormatProvider format = new CultureInfo("vi-VN").DateTimeFormat;
            DateTime dateStart = DateTime.Parse(startDate, format);
            DateTime dateEnd = DateTime.Parse(endDate, format);
            AccountLocation al = new AccountLocation()
            {
                StartDate = dateStart,
                EndDate = dateEnd
            };            
            alList.Add(al);

            return _presenter.UpdateLocationInfo(locationList, alList);
        }

        [OperationContract]
        public void DeleteUploadTemps(string filename, string folder)
        {
            string path = HostingEnvironment.MapPath("~/Files/"+ folder +"/Temps");
            if (!string.IsNullOrEmpty(path) && !string.IsNullOrEmpty(filename))
            {
                string[] lstFile = System.IO.Directory.GetFiles(path);
                foreach (string file in lstFile)
                {
                    string name = file.Substring(file.LastIndexOf("\\") + 1);
                    if(name == filename)
                        System.IO.File.Delete(file);
                }
            }
        }        

        [OperationContract]
        public void Unfriend(string currentID, string friendID)
        {
            if (!string.IsNullOrEmpty(currentID) && !string.IsNullOrEmpty(friendID))
            {
                // Delete Message
                IMessageService _messageService = new MessageService();
                _messageService.DeleteMessageByAccountID(Convert.ToInt32(currentID), Convert.ToInt32(friendID));

                // Delete Message chat
                IMessageChatService _messageChatService = new MessageChatService();
                _messageChatService.DeleteMessageChatByAccountID(Convert.ToInt32(currentID), Convert.ToInt32(friendID));

                // Unfriend
                IFriendService _friendService = new FriendService();
                _friendService.DeleteFriendByAccountID(Convert.ToInt32(currentID), Convert.ToInt32(friendID));                
            }
        }

        //================================= Admin Page ==========================================

        [OperationContract]
        public string UpdateMember_AdminPage(string accountID, string levelID, string isLock)
        {
            if (!string.IsNullOrEmpty(accountID) && !string.IsNullOrEmpty(levelID) && !string.IsNullOrEmpty(isLock))
            {
                IAccountService _accountService = new AccountService();
                _accountService.UpdateMember_AdminPage(Convert.ToInt32(accountID), Convert.ToInt32(levelID), Convert.ToBoolean(isLock));
                return "ok";
            }
            return "";
        }

        [OperationContract]
        public string DeleteMember_AdminPage(string accountID)
        {
            if (!string.IsNullOrEmpty(accountID))
            {

                IProfileService _profileService = new ProfileService();
                _profileService.DeleteProfileByAccountID(Convert.ToInt32(accountID));

                IAccountService _accountService = new AccountService();
                _accountService.DeleteAccountByAccountID(Convert.ToInt32(accountID));
                return "ok";
            }
            return "";
        }

        [OperationContract]
        public string ResetPasswordMember_AdminPage(string accountID, string passReset)
        {
            if (!string.IsNullOrEmpty(accountID) && !string.IsNullOrEmpty(passReset))
            {
                IAccountService _accountService = new AccountService();
                string plaintext = _accountService.GetPlainTextByAccountID(Convert.ToInt32(accountID));
                if (!string.IsNullOrEmpty(plaintext))
                {
                    passReset = Extensions.Encrypt(passReset, plaintext);
                    bool update = _accountService.UpdatePassword(Convert.ToInt32(accountID), passReset);
                    if (update)
                        return "ok";
                }
            }
            return "";
        }
    }
}
